package com.company.bookstore.exception.user_admin_module;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.company.bookstore.common.result.MvcResult;
import com.company.bookstore.entities.user_admin_module.Schedule;
import com.company.bookstore.schedule.ScheduleController;
import com.company.bookstore.service.user_admin_module.ScheduleService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * GlobalCustomExceptionHandler
 *
 * @blame Android Team
 */
@ControllerAdvice
@Slf4j
public class GlobalCustomExceptionHandler {
    @Resource
    ScheduleService scheduleService;
    @ExceptionHandler(value = CustomException.class)
    @ResponseBody
    public  MvcResult<Object> customExceptionHandle(CustomException e){
        log.error("global:发生业务异常！原因是：{}",e.getMessage());
        return MvcResult.builder().code(e.getCode()).message(e.getMessage()).build();
    }

    @ExceptionHandler(value = AccessDeniedException.class)
    @ResponseBody
    public  MvcResult<Object> AccessDeniedExceptionHandle(AccessDeniedException e){
        log.error("global:发生业务异常！原因是：{}",e.getMessage());
        return MvcResult.builder().code(403).message("权限不足").build();
    }

    @ExceptionHandler(value = SchedulerException.class)
    @ResponseBody
    public  MvcResult<Object> SchedulerExceptionHandle(SchedulerException e){
        log.error("global:发生业务异常！原因是：{}",e.getMessage());
        return MvcResult.builder().code(500).message("发生异常，无法开启定时任务").build();
    }
    @ExceptionHandler(value = CustomSecondKillEndException.class)

    public void JobExecutionExceptionHandle(CustomSecondKillEndException e){

        String name =e.getJobExecutionContext().getJobDetail().getKey().getName();

        ScheduleController.removeTask(name);
        scheduleService.remove(new QueryWrapper<Schedule>().eq("name",name));
    }
    @ExceptionHandler(value = JobExecutionException.class)

    public void JobExecutionExceptionHandle(JobExecutionException e){
        log.error("global:发生业务异常！原因是：{}",e.getMessage());
        log.error("发生异常，定时任务中断");
    }
}
